#include <stdio.h>
int a[400];
int time[20][20] = {0}, min = 0;
int eng[20][20] = {0};
int flag[20] = {0};
int machine[20] = {0}, machine_time[20][10000] = {0};
int find(int x)
{
	int i, j, t, p;
	j = machine[x] - 1;
	t = eng[x][flag[x]];
	p = 0;
	while(p == 0)
	{
		j++;
		p = 1;
		while(machine_time[t][j] != 0)
			j++;
		for(i = 0; i < time[x][flag[x]]; i++)
			if(machine_time[t][i+j] == 1) 
			{
				p = 0;
				break;
			}
	}
	return j;
}
int main()
{
	int m, n, i, j, t;
	scanf("%d %d", &m, &n);
	getchar();
	for(i = 0; i < n * m; i++)
	{
		scanf("%d", &a[i]);
		a[i]--;
		getchar();
	}
	for(i = 0; i < n; i++)
		for(j = 0; j < m; j++)			
		{
			scanf("%d", &eng[i][j]);
			eng[i][j]--;
			getchar();
		}
	for(i = 0; i < n; i++)
		for(j = 0; j < m; j++)			
		{
			scanf("%d", &time[i][j]);
			getchar();
		}
	for(i = 0; i < n * m; i++)
	{
		t =	find(a[i]);
		machine[a[i]] = t + time[a[i]][flag[a[i]]];
		for(j = t; j < machine[a[i]]; j++)
			machine_time[eng[a[i]][flag[a[i]]]][j] = 1;
		flag[a[i]]++;
		if(min < machine[a[i]])
			min = machine[a[i]];
	}
	printf("%d\n", min);
	return 0;
}

